package hello

import (
	"appengine"
	"appengine/datastore"
	"time"
)

type RecipeComment struct {
	Id int64
	RecipeId int64
	Text string
	Author string
	DateCreated time.Time
}

func createCommentKey(c *appengine.Context) (key *datastore.Key) {
	key = datastore.NewIncompleteKey(*c, "RecipeComment", nil)
	return
}

func restoreCommentKey(c *appengine.Context, id int64) (key *datastore.Key) {
	key = datastore.NewKey(*c, "RecipeComment", "", id, nil)
	return
}

func listAllComments(c *appengine.Context, recipeId int64) []*RecipeComment {
	q := datastore.NewQuery("RecipeComment").Filter("RecipeId =", recipeId)
	comments := make([]*RecipeComment, 0)
	_, err := q.GetAll(*c, &comments)
	panicIfErr(err)
	return comments
}

func saveRecipeComment(c *appengine.Context, recipeId int64, comment *RecipeComment) (key *datastore.Key) {
	comment.RecipeId = recipeId
	comment.DateCreated = time.Now()
	key, err := datastore.Put(*c, createCommentKey(c), comment)
	panicIfErr(err)
	comment.Id = key.IntID()
	datastore.Put(*c, key, comment)
	panicIfErr(err)
	return key
}

func deleteRecipeComment(c *appengine.Context, id int64) {
	err := datastore.Delete(*c, restoreCommentKey(c, id))
	panicIfErr(err)
}